package com.szgr.baoyin.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.MySaveListAdapter;
import com.szgr.baoyin.model.FavoriteGoods;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MySaveActivity extends BaseActivity implements AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {

    private List<FavoriteGoods> data;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 99:
                    DialogUtils.hideLoadingDialog();
                    saveList.setVisibility(View.GONE);
                    rlNoRecord.setVisibility(View.VISIBLE);
                    break;
                case 100:
                    DialogUtils.hideLoadingDialog();
                    saveList.setVisibility(View.VISIBLE);
                    rlNoRecord.setVisibility(View.GONE);
                    break;
                case 101:
                    getGoodsList();
                    break;
            }
        }
    };
    private MySaveListAdapter listAdapter;
    private Dialog dialog;
    private FavoriteGoods favoriteGoods;
    private RelativeLayout rlNoRecord;
    private ListView saveList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_save);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("我的收藏");
    }

    @Override
    public void initView() {
        data = new ArrayList<>();
        rlNoRecord = (RelativeLayout) findViewById(R.id.save_no_record);
        saveList = (ListView) findViewById(R.id.my_save_list_view);
        listAdapter = new MySaveListAdapter(this, data);
        saveList.setAdapter(listAdapter);
        saveList.setOnItemLongClickListener(this);
        saveList.setOnItemClickListener(this);

        getGoodsList();

        View view = LayoutInflater.from(this).inflate(R.layout.layout_save_goods_dialog,null,false);
        view.findViewById(R.id.save_goods_delete).setOnClickListener(this);
        view.findViewById(R.id.save_goods_cancel).setOnClickListener(this);
        dialog = MyTool.getCenterDialog(this, view);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.save_goods_delete:
                dialog.dismiss();
                deleteSaveGoods(favoriteGoods.getGoods_id());
                break;
            case R.id.save_goods_cancel:
                dialog.dismiss();
                break;
        }
    }

    /**
     * 收藏商品的列表
     */
    private void getGoodsList() {
        DialogUtils.showLoadingDialog(this,"正在加载...");
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_FAVORITE_GOODS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("------>" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if(jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                JSONArray favorites_list = datas.getJSONArray("goods_list");
                                Gson gson = new Gson();
                                data = gson.fromJson(favorites_list.toString(), new TypeToken<List<FavoriteGoods>>() {
                                }.getType());
                                listAdapter.setData(data);
                                if(data.size() > 0){
                                    mHandler.sendEmptyMessage(100);
                                }else if(data.size() == 0){
                                    mHandler.sendEmptyMessage(99);
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToastUtils.showToast("获取收藏列表失败");
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                map.put("page", "1");
                map.put("pagesize", "100");
                map.put("imgsize", "240");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if(data != null){
            favoriteGoods = data.get(position);
            dialog.show();
        }
        return true;
    }

    private void deleteSaveGoods(final String goods_id) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_DELETE_SAVE_GOODS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("---delete save--->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String datas = jsonObject.getString("datas");
                            if("1".equals(datas)){
                                mHandler.obtainMessage(101).sendToTarget();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("key",MyApplication.getmInstance().getKey());
                map.put("fav_id",goods_id);
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FavoriteGoods favoriteGoods = data.get(position);
        Intent intent = new Intent(this, StoreDeatilActivity.class);
        intent.putExtra("goods_id",favoriteGoods.getGoods_id());
        startActivity(intent);
    }
}
